//
//  FriendViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "FriendViewController.h"
#import "YSCommon.h"
#import "FriendTableViewCell.h"
#import "ChatViewController.h"
#import <XAISDK/XAI.h>
#import "MQTTSessionManager.h"
#import "UIBarButtonItem+Extension.h"
#import "AuthoritySettingController.h"
#import "MQTTSessionManager.h"
#import "ZTDevice.h"
#import "Friend.h"
#import "PermissionsUtils.h"
#import "QRCoderViewController.h"
#import "UIView+HUD.h"

static NSString* const FriendCellIdentfier = @"FriendCellIdentfier";
@interface FriendViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
DataManagerRefreshDelegate,
MGSwipeTableCellDelegate
>
@property (nullable, nonatomic, strong) UITableView* mTbaleView;
@property (nullable, nonatomic, strong) NSArray* datasources;
@property (nullable, nonatomic, strong) UINavigationBar* navigationBar;
@property (nullable, nonatomic, strong) UINavigationItem *titleItem;
@end

@implementation FriendViewController


#pragma mark - life cycle
- (void)dealloc {
    [kDataManager removeFriendRefreshDelegate:self];
    [kDataManager removeIMMessageRefreshDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [kDataManager addFriendRefreshDelegate:self];
    [kDataManager addIMMessageRefreshDelegate:self];
    [self refreshFriendList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - event resonse 
- (void)didTappedAddFriendButton {

    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status)
    {
        case AVAuthorizationStatusNotDetermined:
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted)
                {
                    __weak typeof(self) wself = self;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        __strong typeof(wself)sself = wself;
                        if (!sself) {
                            return ;
                        }
                        [sself entertoQrCodeVC];
                    });
                } else {
                    debugLogInfo(@"用户拒绝");
                }
            }];
        }
            break;
        case AVAuthorizationStatusAuthorized:
        {
            // 已经开启授权，可继续
            [self entertoQrCodeVC];
        }
            break;
        case AVAuthorizationStatusDenied:
        {
            UIAlertView* alerView = [[UIAlertView alloc]initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" delegate:self cancelButtonTitle:@"好" otherButtonTitles:@"设置", nil];
            [alerView show];
        }
            break;
        case AVAuthorizationStatusRestricted:
        {
            [self.view yh_showMsgHUD:@"相机设备无法访问"];
        }
            break;
        default:
            break;
    }
}

#pragma mark - DataManagerRefreshDelegate

- (void)friendRefresh:(DataManager *)manager callbackType:(FriendCallbackType)callbackType {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self refreshFriendList];
    });
}

- (void)imMessageRefresh:(DataManager *)manager {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mTbaleView reloadData];
    });
}

#pragma mark  - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datasources.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FriendTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:FriendCellIdentfier forIndexPath:indexPath];
    cell.friendModel = self.datasources[indexPath.row];
    cell.rightButtons = [self createRightButtons:2];
    cell.delegate = self;
    return cell;
}

#pragma mark - MGSwipeTableCellDelegate

-(BOOL)swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion {
    debugLogInfo(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
                 direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        return NO;
    }
    else if(direction == MGSwipeDirectionRightToLeft && index == 1) {
        //edit button
        NSIndexPath * indexPath = [self.mTbaleView indexPathForCell:cell];
        Friend* friend = self.datasources[indexPath.row];
        AuthoritySettingController* authoritySettingVC = [[AuthoritySettingController alloc]init];
        authoritySettingVC.mobile = friend.mobile;
        [self.navigationController pushViewController:authoritySettingVC animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark  - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatViewController *chatVC = [[ChatViewController alloc]init];
    chatVC.user = self.datasources[indexPath.row];
    [self.navigationController pushViewController:chatVC animated:YES];
}

#pragma mark - private method

- (void)entertoQrCodeVC {
    QRCoderViewController *QRCoderVc = [QRCoderViewController createQRCoderViewController];
    QRCoderVc.enterVcType = EnterScanControllerTypeAddFriend;
    [self.navigationController pushViewController:QRCoderVc animated:YES];
}

-(NSArray *)createRightButtons:(int)number {
    NSMutableArray * result = [NSMutableArray array];
    NSArray *colors = @[RGBColor(239, 75, 58),RGBColor(204, 204, 204)];
    NSArray *icons = @[[UIImage imageNamed:@"im_delete"], [UIImage imageNamed:@"im_setting_white"]];
    for (int i = 0; i < number; ++i) {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:[icons objectAtIndex:i] backgroundColor:[colors objectAtIndex:i]  padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}

- (void)refreshFriendList {
    self.datasources = kDataManager.friendListenList;
    [self.mTbaleView reloadData];
}

- (void)initSubviews {
    self.view.backgroundColor = kBgColor;
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.mTbaleView];
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews {
    [self.navigationBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.view);
        make.height.equalTo(64);
    }];
    [self.mTbaleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.navigationBar.bottom);
        make.bottom.equalTo(self.view).offset(kIphoneSize_Height(-48));
    }];
}


#pragma mark - getters and setters

- (UITableView *)mTbaleView
{
    if (!_mTbaleView) {
        _mTbaleView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _mTbaleView.showsVerticalScrollIndicator = NO;
        _mTbaleView.showsHorizontalScrollIndicator = NO;
        _mTbaleView.delegate = self;
        _mTbaleView.dataSource = self;
        _mTbaleView.rowHeight = kIphoneSize_Height(68);
        _mTbaleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mTbaleView.backgroundColor = kBgColor;
        [_mTbaleView registerClass:[FriendTableViewCell class] forCellReuseIdentifier:FriendCellIdentfier];
    }
    return _mTbaleView;
}

- (UINavigationBar *)navigationBar {
    if (!_navigationBar) {
        _navigationBar = [[UINavigationBar alloc]init];
        [_navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBarbackgroundImage"] forBarMetrics:UIBarMetricsDefault];
        NSMutableDictionary *barTextAttrs = [NSMutableDictionary dictionary];
        barTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
        barTextAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];
        [_navigationBar setTitleTextAttributes:barTextAttrs];
        _navigationBar.items = @[self.titleItem];
    }
    return _navigationBar;
}

- (UINavigationItem *)titleItem
{
    if (!_titleItem) {
        _titleItem = [[UINavigationItem alloc]init];
        _titleItem.rightBarButtonItem =  [UIBarButtonItem createBarbuttonItem:@"im_add" target:self action:@selector(didTappedAddFriendButton)];
        _titleItem.title = @"好友聊天";
    }
    return _titleItem;
}

@end
